<?php


namespace app\admin\controller;

use app\admin\model\ResourceFile;
use app\admin\model\ResourceFolder;
use app\admin\model\WechatDepartment;
use app\admin\model\WechatUser;
use app\admin\model\WechatUserTag;
use think\Db;

/**
 * 资源管理
 * Class Resource
 * @package app\admin\controller
 */
class Resource extends Admin
{
    protected function _initialize(){
        $user_old = session('user_auth');
        if($user_old['userId'] == "admin") {
            $user = \app\home\model\WechatUserTag::where(['tagid' => 1])->find();
            $user_new = $this->getTopDepartment($user['userid']);
        }else {
            $user_new = $this->getTopDepartment($user_old['userId']);
        }
        $userId = $this->userid = $user_new['userid'];
        //权限，1领导，2科室长，3普通员工
        if($userId == "admin") {
            $permission = 1;
        }else {
            $res = WechatUserTag::where(['userid' => $userId])->find();
            if($res) {
                switch ($res['tagid']) {
                    case 1: //总经理
                        $permission = 1;
                        break;
                    case 2: //副总
                        $permission = 1;
                        break;
                    case 3: //科室长
                        $permission = 2;
                        break;
                    default: //普通员工
                        $permission = 3;
                        break;
                }
            }else {
                $permission = 3;
            }
        }
        $user_new['permission'] = $permission;
        $this->user = $user_new;
        parent::_initialize();
    }
    /**
     * 文件夹列表页
     */
    public function folder() {
        $user_data = $this->user;
        //一级部门文件夹
        $department = Db::table('zm_wechat_department')->where(['parentid' => 1])->order('`order` desc')->select();
        foreach ($department as $key => $value) {
            $map = [
                'pid' => 0,
                'top_id' => $value['id'],
                'status' => ['egt',0]
            ];
            $second = Db::table('zm_resource_folder')->where($map)->select();
            foreach ($second as $k => $v) {
                $map2 = [
                    'pid' => $v['id'],
                    'status' => ['egt',0]
                ];
                $three = Db::table('zm_resource_folder')->where($map2)->select();
                $second[$k]['children'] = $three;
            }
            $department[$key]['children'] = $second;
        }
        $this->assign('department',json_encode($department));
        $this->assign('user_data',json_encode($user_data));

        return $this->fetch();
    }

    /**
     * 新增
     */
    public function folderadd() {
        $Model = new ResourceFolder();
        if(IS_POST) {
            $data = input('post.');
            $map = [
                'pid' => $data['pid'],
                'top_id' => $data['top_id'],
                'name' => $data['name']
            ];
            $exists = $Model->where($map)->find();
            if($exists) {
                return $this->error("存在相同文件夹名称，请重新命名!");
            }else {
                $res = $Model->create($data);
                if($res) {
                    return $this->success("创建成功","",$res);
                }else {
                    return $this->error("创建失败");
                }
            }
        }
    }

    /**
     * 修改
     */
    public function folderedit() {
        $Model = new ResourceFolder();
        if(IS_POST) {
            $id = input('id');
            $data = input('post.');
            $data['update_time'] = time();
            $map = [
                'pid' => $data['pid'],
                'top_id' => $data['top_id'],
                'name' => $data['name']
            ];
            $exists = $Model->where($map)->where('id', '<>', $id)->find();
            if($exists) {
                return $this->error("存在相同文件夹名称，请重新命名!");
            }else {
                $res = $Model->update($data,['id' => $id]);
                if($res) {
                    return $this->success("更新成功","",$res);
                }else {
                    return $this->error("更新失败");
                }
            }
        }
    }

    /**
     * 文件夹删除
     */
    public function folderdel() {
        $folderModel = new ResourceFolder();
        $fileModel = new ResourceFile();

        $id = input('id');
        $data = ['status' => -1 ];
        $res = $folderModel->where('id',$id)->update($data);
        if($res) {
            $fileModel->where('folder_id',$id)->update($data);
            $res2 = $folderModel->where('pid',$id)->select();
            if($res2) {
                $folderModel->where('pid',$id)->update($data);
                foreach ($res2 as $value) {
                    $fileModel->where('folder_id',$value['id'])->update($data);
                    $res3 = $folderModel->where('pid',$value['id'])->find();
                    $folderModel->where('pid',$value['id'])->update($data);
                    if($res3) {
                        $fileModel->where('folder_id',$res3['id'])->update($data);
                    }
                }
            }
            return $this->success("删除成功");
        }else {
            return $this->error("删除失败");
        }
    }

    /**
     * 文件列表
     */
    public function file() {
        $user = $this->user;
        $fileModel = new ResourceFile();
        $folder_id = input('folder_id'); //文件夹id
        $page = input('page',1); //当前页面
        if(IS_POST) {
            $length = ($page - 1) * 10;
            $map = [
                'userid' => $user['userid'],
                'folder_id' => $folder_id,
                'status' => ['egt',0]
            ];
            $data = $fileModel->where($map)->limit($length,10)->order('update_time desc,create_time desc')->select();
            $count = $fileModel->where($map)->count();
            foreach ($data as $key => $value) {
                $data[$key]['update_time'] = $value['update_time'] ? date("Y-m-d H:i",$value['update_time']) : date("Y-m-d H:i",$value['create_time']);
                $file = \app\admin\model\File::where(['id' => $value['file_id']])->find();
                $data[$key]['file_name'] = $file ? $file['name'] : '';
                $data[$key]['file_type'] = $file ? $file['ext'] : '';
                $data[$key]['file_size'] = $file ? $this->sizecount($file['size']) : '';
            }
            $list = [
                'data' => $data, //当前数据
                'count' => $count, //数据总数
                'page' => $page //当前页码
            ];
            if($list) {
                return $this->success("获取成功","",$list);
            }else {
                return $this->error("获取失败");
            }
        }
    }

    /**
     * 添加文件
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fileadd() {
        $user = $this->user;
        $fileModel = new ResourceFile();
        if(IS_POST) {
            $data = input('post.');
            $data['userid'] = $user['userid'];
            $data['username'] = $user['username'];
            $map = [
                'folder_id' => $data['folder_id'],
                'name' => $data['name']
            ];
            $exists = $fileModel->where($map)->find();
            if($exists) {
                return $this->error("存在相同文件名称，请重新命名!");
            }else {
                $res = $fileModel->create($data);
                if($res) {
                    $res['update_time'] = $res['update_time'] ? date("Y-m-d H:i",$res['update_time']) : date("Y-m-d H:i",$res['create_time']);
                    $file = \app\admin\model\File::where(['id' => $res['file_id']])->find();
                    $res['file_name'] = $file ? $file['name'] : '';
                    $res['file_type'] = $file ? $file['ext'] : '';
                    $res['file_size'] = $file ? $this->sizecount($file['size']) : '';
                    return $this->success("创建成功","",$res);
                }else {
                    return $this->error("创建失败");
                }
            }
        }
    }

    /**
     * 修改文件
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fileedit() {
        $fileModel = new ResourceFile();
        if(IS_POST) {
            $id = input('id');
            $data = input('post.');
            $data['update_time'] = time();
            $map = [
                'folder_id' => $data['folder_id'],
                'name' => $data['name']
            ];
            $exists = $fileModel->where($map)->where('id', '<>', $id)->find();
            if($exists) {
                return $this->error("存在相同文件夹名称，请重新命名!");
            }else {
                $res = $fileModel->where(['id' => $id])->update($data);
                if($res) {
                    $res['update_time'] = $res['update_time'] ? date("Y-m-d H:i",$res['update_time']) : date("Y-m-d H:i",$res['create_time']);
                    $file = \app\admin\model\File::where(['id' => $res['file_id']])->find();
                    $res['file_name'] = $file ? $file['name'] : '';
                    $res['file_type'] = $file ? $file['ext'] : '';
                    $res['file_size'] = $file ? $this->sizecount($file['size']) : '';
                    return $this->success("更新成功","",$res);
                }else {
                    return $this->error("更新失败");
                }
            }
        }
    }

    /**
     * 文件删除
     */
    public function filedel() {
        $fileModel = new ResourceFile();
        $id = input('id');
        $data = ['status' => -1 ];
        $res = $fileModel->where('id',$id)->update($data);
        if($res) {
            return $this->success("删除成功");
        }else {
            return $this->error("删除失败");
        }
    }

    /**
     * 获取当前用户所属科室
     */
    public function getTopDepartment($userid) {
        $userModel = new WechatUser();
        $departmentModel = new WechatDepartment();
        $user = $userModel->where(['userid' => $userid])->find();
        $department = $departmentModel->where(['id' => $user['department']])->find();
        $depart = $department['id'];
        //查找顶级部门id
        if($department['parentid'] == 1) {
            $top_depart = $department['id'];
        }else {
            $department2 = $departmentModel->where(['id' => $department['parentid']])->find();
            if($department2['parentid'] == 1) {
                $top_depart = $department2['id'];
            }else {
                $department3 = $departmentModel->where(['id' => $department2['parentid']])->find();
                if($department3['parentid'] == 1) {
                    $top_depart = $department3['id'];
                }else {
                    return $this->error("查找不到该用户所在科室！");
                }
            }
        }
        $return = [
            'userid' => $userid,
            'username' => $user['name'],
            'topid' => $top_depart,
            'departmentid' => $depart,
        ];
        return $return;
    }

    /**
     * 转化文件大小
     */
    private function sizecount($filesize) {
        if($filesize >= 1073741824) {
            $filesize = round($filesize / 1073741824 * 100) / 100 . ' gb';
        } elseif($filesize >= 1048576) {
            $filesize = round($filesize / 1048576 * 100) / 100 . ' mb';
        } elseif($filesize >= 1024) {
            $filesize = round($filesize / 1024 * 100) / 100 . ' kb';
        } else {
            $filesize = $filesize . ' bytes';
        }
        return $filesize;
    }
}